package com.l.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.l.entity.User;
import com.l.service.LoginService;
import com.l.utils.BuildcodeUtil;
import com.l.utils.Maputil;
import com.l.utils.Msg;

/**
 * 手机号注册，三方登录
 * 
 * @author xuejie
 * 
 */
@RestController
public class LoginController {
	@Autowired
	LoginService loginService;
	private static List<Map<String, Object>> mmmlist = new ArrayList<Map<String, Object>>();

	// 生成验证码
	@RequestMapping("/buildcode")
	@ResponseBody
	public Msg buildcode(String mobile) throws Exception {

		Map<String, Object> m2 = new HashMap<String, Object>();
		// 生成验证码(6位随机的验证码)
		String random = String
				.valueOf((int) ((Math.random() * 9 + 1) * 100000));
		System.out.println(mobile + " ~~~" + random);
		// 第三方发送短息
		BuildcodeUtil.buildcode(mobile, random, 1);
		// 将随机验证码放入到全局map中
		m2.put("random", random);
		m2.put("mobile", mobile);
		mmmlist.add(m2);
		m2 = new HashMap<String, Object>();

		return Msg.success().add("code", random);
	}

	// 注册
	@RequestMapping("/registeriface")
	@ResponseBody
	public Msg registeriface(User user, String code) {
		// 生成的随机码为random
		String random = Maputil.getmapvalue(mmmlist, user.getZhanghao());
		if (code.equals(random)) {// 如果输入的验证码和生成的随机码相同，则注册
			// 注册方法
			int i = loginService.loginphone(user);
			if (i > 0) {
				// 验证码用后失效
				Map<String, String> map = new HashMap<String, String>();
				map.put("mobile", user.getZhanghao());
				map.put("random", random);
				mmmlist.remove(map);
				return Msg.success().add("data", "注册用户成功");
			} else {
				return Msg.fail().add("data", "注册用户失败");
			}
		} else {
			return Msg.fail().add("data", "验证码不正确");
		}
	}
}
